import {
  clearObject,
  deepCopyObj
} from '../../../assets/js/help.js'
import api from '../../../fetch/api'

export default {
  data() {
    var validateChannelSeqList = (rule, value, callback) => {
      if (value === null || value.length === 0) {
        return callback(new Error('请选择通道权限'));
      }
      return callback();
    };

    var validateParkId = (rule, value, callback) => {
      if (value == null || value.length == '') {
        return callback(new Error('请选择停车场'));
      }
      return callback();
    };

    var validatePriTimeArr = (rule, value, callback) => {
      if (value == null || value == '' || value == ',') {
        return callback(new Error('请选择可销售时间'));
      }
      return callback();

    };

    var validateInt = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('不能为空'));
      }
      if (!/^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error('请输入大于0的整数'));
      }
      return callback();

    };

    var validateSettlementAmount = (rule, value, callback) => {
      var self = this;
      var settleType = self.vipTypeEditModel.settlementType;
      if (settleType == '0' || settleType == '1') {
        if (value === null || value === '') {
          return callback(new Error('请输入金额'));
        }
        if (value === 0) {
          return callback();
        }
        if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/.test(value)) {
          return callback(new Error('请输入正确的金额'));
        } else {
          if (value < 0) {
            return callback(new Error('金额不能小于0'));
          } else {
            return callback();
          }
        }
      } else {
        if (value === null || value === '') {
          return callback(new Error('次数不能为空'));
        }
        if (!/^[1-9]+[0-9]*$/.test(value)) {
          return callback(new Error('请输入大于0的次数'));
        }
      }
      return callback();

    };
    var today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 23:59:59'))];

    return {
      privilegeDate: {
        theadsInfo: [{
            index: 0,
            isShow: false,
            prop: 'reno',
            text: '序号',
            minWidth: 60
          },
          {
            index: 1,
            isShow: false,
            prop: 'date',
            text: '日期',
            minWidth: 120
          }
        ],
        bodysInfo: ''
      },
      editModelTitle: '',
      editModelReadonly: false,
      vipTypeNewModel: {
        id: null,
        customVipName: '',
        settlementType: 0,
        settlementAmount: null,
        isDynamicMode: 0,
        dynamicCarportNumber: null,
        isDatePrivilege: 0,
        isTimePrivilege: 0,
        privilegeTimePeriod: null,
        isChargeGroupRelated: 0,
        chargeGroupCode: null,
        vipGroupType: 0,
        dynamicFullLimit: 0,
        dynamicCarNumber: null,
        vipNearExpiredDayThreshold: '10',
        openVipFullLimit: 0,
        vipFullLimitValue: null,
        vipRecoverTime: null,
        priTimeArr: today,
        priDateArrStr: '',
        parkId: '',
        parkName: '',
        channelAuthTree: '',
        channelSeqList: []
      },
      vipTypeEditModel: '',
      vipTypeRules: {
        customVipName: [{
            required: true,
            message: '名称不能为空',
            trigger: 'change'
          },
          {
            min: 2,
            max: 30,
            message: '长度在 2 到 30 个字符',
            trigger: 'change'
          }
        ],
        // vipGroupType: [
        //     { required: true, message: '不能为空', trigger: 'change' }
        // ],
        parkId: [{
            validator: validateParkId,
            trigger: 'change'
          }
          // { required: true, message: '请选择停车场', trigger: 'change' }
        ],
        channelSeqList: [{
          validator: validateChannelSeqList,
          trigger: 'change'
        }],
        // settlementType: [
        //     { required: true, message: '不能为空', trigger: 'change' }
        // ],
        settlementAmount: [{
          validator: validateSettlementAmount,
          trigger: 'change'
        }],
        dynamicCarportNumber: [{
          validator: validateInt,
          trigger: 'change'
        }],
        vipFullLimitValue: [{
          validator: validateInt,
          trigger: 'change'
        }],
        priDateArrStr: [{
          required: true,
          message: '请设置日期表',
          trigger: 'change'
        }],
        priTimeArr: [{
          validator: validatePriTimeArr,
          trigger: 'change'
        }],
        vipNearExpiredDayThreshold: [{
          validator: validateInt,
          trigger: 'change'
        }],
        chargeGroupCode: [{
          required: true,
          message: '计费组编号不能为空',
          trigger: 'change'
        }],

      },
    }
  },
  watch: {
    'vipTypeEditModel.channelSeqList': function (value) {
      if (this.$refs.form_Add) {
        this.$refs.form_Add.validateField('channelSeqList');
      }
    },
    'vipTypeEditModel.parkId': function (value) {
      if (this.$refs.form_Add) {
        this.$refs.form_Add.validateField('parkId');
      }
    },
    'vipTypeEditModel.settlementType': function (value) {
      if (this.$refs.form_Add) {
        this.$refs.form_Add.validateField('settlementAmount');
      }
    },
    'vipTypeEditModel.priDateArrStr': function (value) {
      if (this.$refs.form_Add) {
        this.$refs.form_Add.validateField('priDateArrStr');
      }
    },
    priTimeArrValue: function (value) {
      this.vipTypeEditModel.priTimeArr = value;
    }

  },
  created() {

    // this.getList();
  },
  filters: {
    formatDate(val) {
      return new Date(val).Format("yyyy-MM-dd");
    },
    formatSettlementAmount(settlementAmount, settlementType) {
      if (settlementType == 0) {
        return settlementAmount + "元/月";
      }
      if (settlementType == 1) {
        return "充值比例：" + settlementAmount;
      }
      if (settlementType == 2) {
        return settlementAmount + "元/次";
      }
    },
    isChargeGroupRelatedShow(value) {
      if (value == 1) {
        return "是";
      }
      return "否";
    }
  },
  methods: {
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.list(params);
    },
    list(aparams) {
      let _this = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.park_vip.vipTypeList(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          _this.tbodysInfo = list;
          _this.total = data.total;
        }, err => {})
    },
    //list end
    showAccessPrivilege(vipType) {
      var _this = this;
      let params = {
        id: vipType.id
      }
      _this.toOpenModal("privilegeTreeModal", 1);
      API.park_vip.vipTypeShowPrivilege(params).then(res => {
        var data = res;
        getPrivilegeTreeCallback(data);
      }, err => {})

      function getPrivilegeTreeCallback(data) {
        if (data.status == 1) {
          var nodes = data.data;
          //_this.setNodeChkDisabled(nodes,true);
          var settings = {
            check: {
              enable: true,
              chkboxType: {
                "Y": "",
                "N": ""
              }
            },
            data: {
              key: {
                checked: "checked",
                chkDisabled: true,
                children: "childrenList",
              }
            },
            view: {
              showIcon: false,
              showLine: false,
            }
          };
          $.fn.zTree.destroy("accessPrivilegeTree");
          $.fn.zTree.init($("#accessPrivilegeTree"), settings, nodes);
          var treeObj = $.fn.zTree.getZTreeObj("showAccessPrivilegeTree");
          // treeObj.expand('true');

        } else {
          _this.showToast(data.msg, 2);
        }
      }
    },
    //showAccessPrivilege end
    AddModal_open() {
      let _this = this;
      this.editModelTitle = "新增";
      this.editModelReadonly = false;
      this.priTimeArrValue = [new Date('1997-01-01 00:00:00'), new Date('1997-01-01 23:59:59')];
      _this.vipTypeEditModel = deepCopyObj(_this.vipTypeNewModel);
      _this.vipTypeEditModel.priTimeArr = _this.vipTypeNewModel.priTimeArr;
      _this.isMoreRules = true;
      _this.toOpenModal('AddModal', 1);
    },
    modelEdit(vipType, editModelReadonly) {
      var _this = this;
      this.editModelTitle = "修改";
      if (editModelReadonly) {
        this.editModelReadonly = editModelReadonly;
      } else {
        this.editModelReadonly = false;
      }
      var params = {
        vipTypeId: vipType.id
      };
      api.fetchGet('/vip/vipType/getById.do', params).then(res => {
        if (res.status == 1) {
          _this.vipTypeEditModel = res.data;
          _this.toOpenModal('AddModal', 1);
          if (res.data.privilegeTimePeriod) {
            _this.priTimeArrValue = [new Date(moment().format('YYYY-MM-DD ' + res.data.privilegeTimePeriod.split('-')[0] + ':00')), new Date(moment().format('YYYY-MM-DD ' + res.data.privilegeTimePeriod.split('-')[1] + ':00'))];
          } else {
            var priTimeArr = [new Date('1997-01-01 00:00:00'), new Date('1997-01-01 23:59:59')];
            _this.vipTypeEditModel.priTimeArr = priTimeArr;
          }
          _this.initChannelTree(_this.vipTypeEditModel.parkUUID, _this.vipTypeEditModel.id);
          _this.toOpenModal('AddModal', 1);
        } else {
          self.showToast(res.message, 2, 2000)
          return;
        }
      }, err => {})
    },
    submitForm(formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          self.saveVipType();
        } else {
          return false;
        }
      });
    }, //submitForm end
    saveVipType() {
      let self = this;
      var params = deepCopyObj(self.vipTypeEditModel);
      var treeObj = $.fn.zTree.getZTreeObj("channelTree");
      var nodes = treeObj.getNodes();
      params.channelAuthTree = JSON.stringify(nodes);
      params.privilegeTimePeriod = self.vipTypeEditModel.priTimeArr[0].Format("hh:mm") + "-" + self.vipTypeEditModel.priTimeArr[1].Format("hh:mm");

      for (var i in params) {
        if (params[i] === null || params[i] === '') {
          delete params[i];
        }
      }

      api.fetchPost('/vip/vipType/save.do', params).then(res => {
        if (res.status == 1) {
          self.showToast(res.message, 1, 2000);
          self.closed('AddModal', 1);
          self.getList();
        } else {
          self.showToast(res.message, 2, 2000)
          return;
        }
      }, err => {})
    },
    showPrivilegeDate(vipType) {
      var _this = this;
      let params = {
        parkId: vipType.parkId
      }
      //如果vipseq属性没有值则用id代替
      if(vipType.vipSeq){
        params.vipSeq = vipType.vipSeq;
      }else{
        params.vipSeq = vipType.id;
      }
      API.park_vip.vipTypePrivilegeDate(params).then(res => {
        var data = res;
        _this.privilegeDate.bodysInfo = data.data;
        _this.toOpenModal("privilegeDateModal");
      }, err => {})
    },
    setNodeChkDisabled(nodes, value) {
      nodes.map((item) => {
        item['chkDisabled'] = value;
        var childrenList = item.childrenList;
        if (childrenList) {
          this.setNodeChkDisabled(childrenList, value);
        }
      });
    },
    toSelectPark() {
      var _self = this;
      _self.toOpenModal('selectParkModal', 2);
      this.initParkTree("ParkTree");
    }, //toSelectPark end
    initParkTree(treeId) {
      var _this = this;
      API.monthTicket.getParkTree({}).then(res => {
        //start..
        var data = res;
        if (data != null) {
          var nodes = data.data;
          var jsonStr = JSON.stringify(nodes);

          jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
          nodes = JSON.parse(jsonStr);
          var settings = {
            check: {
              enable: true,
              chkStyle: "radio",
              radioType: "all"
            },
            view: {
              showIcon: false,
              showLine: false,
            },
            callback: {
              onClick: function (event, treeId, treeNode) {
                var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                treeObj.checkNode(treeNode, true, false);
                if (treeNode.isArea) {
                  return;
                }
              },
            }
          };
          $.fn.zTree.destroy("ParkTree");
          var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
          var treeObj = $.fn.zTree.getZTreeObj("ParkTree");

          if (_this.vipTypeEditModel.parkId) {
            var node = treeObj.getNodeByParam("value", _this.vipTypeEditModel.parkId);
            if (node) {
              if (node.getParentNode() && !node.getParentNode().open) {
                treeObj.expandNode(node.getParentNode(), true, true, true);
              }
              treeObj.checkNode(node, true, true);
            }
          }
          treeObj.expandAll(true);

        } else {
          _this.showToast('暂时没有停车场可选', 2, 3000);
        }
        //end..
      }, err => {})

    },
    initChannelTree(parkId, vipTypeId) {
      var self = this;
      var params = {
        parkId: parkId,
        vipTypeId: vipTypeId
      };
      api.fetchPost('/vip/vipType/getChannelAuthTree.do', params).then(res => {
        if (res.status == 1) {
          //start..
          var data = res;
          if (data != null) {
            var nodes = res.data;
            var settings = {
              check: {
                enable: true,
                chkboxType: {
                  "Y": "",
                  "N": ""
                }
              },
              data: {
                key: {
                  checked: "checked",
                  chkDisabled: true,
                  children: "childrenList",
                }
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('channelTree');
                  if (treeNode.checked) {
                    treeObj.checkNode(treeNode, false, false);
                  } else {
                    treeObj.checkNode(treeNode, true, false);
                  }
                  var channelSeqList = [];
                  var checkedNodes = treeObj.getCheckedNodes(true);
                  for (var i = 0; i < checkedNodes.length; i++) {
                    channelSeqList.push(checkedNodes[i].channelSeq);
                  }
                  self.$set(self.vipTypeEditModel, 'channelSeqList', channelSeqList);
                },
                onCheck: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('channelTree');
                  var channelSeqList = [];
                  var checkedNodes = treeObj.getCheckedNodes(true);
                  for (var i = 0; i < checkedNodes.length; i++) {
                    channelSeqList.push(checkedNodes[i].channelSeq);
                  }
                  self.$set(self.vipTypeEditModel, 'channelSeqList', channelSeqList);
                }
              }
            };
            $.fn.zTree.destroy("channelTree");
            $.fn.zTree.init($("#channelTree"), settings, nodes);
            var treeObj = $.fn.zTree.getZTreeObj("channelTree");
            // var nodes = treeObj.getNodes();
            // self.vipTypeEditModel.channelAuthTree = nodes;
            treeObj.expandAll(true);

          } else {
            self.showToast('改停车场没有配置通道', 2, 3000);
          }
          //end..
        } else {
          self.showToast(res.message, 2, 2000)
          return;
        }
      }, err => {})
    },
    selectParkSure() {
      var _this = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      var parkList = new Array();
      // 初始化表格显示数据以及提交的表格参数
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i]);
        }
      }
      if (parkList.length <= 0) {
        _this.showToast('请选择一个停车场', 0);
        return;
      }
      _this.vipTypeEditModel.parkId = parkList[0].value;
      _this.vipTypeEditModel.parkName = parkList[0].name;
      _this.initChannelTree(parkList[0].parkId);
      _this.closed('selectParkModal', 2);
    },
    openCalendar() {
      this.toOpenModal('multiCalendarModal', 2);
    },
    saveCalendar(calendar) {
      this.vipTypeEditModel.priDateArrStr = calendar;
      this.closed('multiCalendarModal', 2);
    },
    delVipType(vipType) {
      var self = this;
      // if (ticket.sellNum > 0 || ticket.ticketStatus == 'VALID') {
      //     return;
      // };
      var params = {
        vipTypeId: vipType.id,
      };
      self.showDialog("确认删除该VIP类型?", '', function () {
        api.fetchPost('/vip/vipType/deleteVipType.do', params).then(res => {
          if (res.status == 1) {
            var data = res;
            self.showToast(res.message, 1);
            self.getList();
          } else {
            self.showToast(res.message, 2, 2000)
            return;
          }
        }, err => {})
      })
    }
  }
}
